﻿using NotificationLib;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace GalacticLib
{
    public class Config
    {

        public Dictionary<string, string> Values { get; set; }
        SqlConnection connection;

        public EmailNotificationConfig EmailSettings;
        public PushoverNotificationConfig PushoverSettings;

        public Config(SqlConnection conn)
        {
            Values = new Dictionary<string, string>();
            connection = conn;


            EmailSettings = new EmailNotificationConfig();

            EmailSettings.MailServer = GetConfigValue("MailServer");
            EmailSettings.MailServerPort = short.Parse(GetConfigValue("MailPort"));
            EmailSettings.FromAddress = new MailAddress(GetConfigValue("MailFrom"), GetConfigValue("MailFromName"));
            EmailSettings.AuthenticationType = EmailNotificationAuthenticationType.UserAndPass;
            EmailSettings.Username = GetConfigValue("MailUser");
            EmailSettings.Password = GetConfigValue("MailPassword");

            PushoverSettings = new PushoverNotificationConfig();
            PushoverSettings.ApiKey = GetConfigValue("PushoverApiKey");
            

        }

        public string GetConfigValue(string key)
        {
            SqlCommand cmd = new SqlCommand();

            cmd.Connection = connection;
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.CommandText = "usp_GetConfigValue";

            SqlParameter p = new SqlParameter("ConfigKey", key);
            cmd.Parameters.Add(p);

            if (cmd.Connection.State == System.Data.ConnectionState.Closed)
                cmd.Connection.Open();

            SqlDataReader reader = cmd.ExecuteReader();
            reader.Read();
            string v = reader["ConfigValue"].ToString();
            reader.Close();
            return v;
        }

        public static string GetConfigValue(SqlConnection conn, string key)
        {
            return GetConfigValue(conn, key);

        }
    }
}
